<template>
  <div>
    <h3 class="title">拖拽上传</h3>
    <div ref="box" class="border_dot">
      <button class="btn update_btn btn_up_drop" @click="handleUpdate">
        上传
      </button>
      <div>请上传PNG/JPG/JPEG类型图片</div>
      <div class="multiple_list_wrap scroll_box" v-if="files.length > 0">
        <div v-for="f in files" :key="f.key">
          <div class="file_item_wrap">
            <span class="file_name">{{ f.filename }}</span>
            <span class="file_remove" @click="handleRemove(f)">移除</span>
          </div>
          <Progress :value="f.progress" />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from "vue";
import { updateFile } from "@/api/update";
const box = ref<null | HTMLDivElement>(null);
interface IFileList {
  file: File;
  filename: string;
  key: number;
  progress: number;
}
const files = ref<IFileList[]>([]);

async function handleUpdate() {
  if (files.value.length === 0) {
    alert("请选择文件");
    return;
  }
  const updateBtn = document.querySelector(".btn_up_drop");
  updateBtn?.setAttribute("loading", "loading");
  const fileList = files.value.map((e) => {
    return new Promise((resolve, reject) => {
      const formData = new FormData();
      formData.append("file", e.file);
      updateFile<FormData, { type: number; path: string }>(formData, {
        onUploadProgress: (ev: ProgressEvent) => {
          e.progress = Math.ceil((ev.loaded / ev.total) * 100);
        },
      })
        .then(resolve)
        .catch(reject);
    });
  });
  try {
    await Promise.all(fileList);
    alert("上传成功");
  } catch (error) {
    alert("上传失败");
  } finally {
    files.value = [];
    updateBtn?.removeAttribute("loading");
  }
}

function handleRemove(f: IFileList) {
  files.value = files.value.filter((e) => e.key !== f.key);
}

onMounted(() => {
  box.value.addEventListener("drop", (ev: DragEvent) => {
    ev.preventDefault();
    files.value = Array.from(ev.dataTransfer.files).map((f) => ({
      progress: 0,
      filename: f.name,
      file: f,
      key: Math.ceil(Math.random() * Date.now()),
    }));
  });
  box.value.addEventListener("dragover", (ev: Event) => {
    ev.preventDefault();
  });
});
</script>

<style></style>
